package com.aiden.architecturecomponenttest.http

import android.util.Log
import com.aiden.architecturecomponenttest.CustomApplication
import com.aiden.architecturecomponenttest.data.service.HospitalService
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

class NetWork {

    private val baseUrl: String = "https://news-at.zhihu.com/api/"
    private val TIME_OUT = 10000L

    companion object {
        var INSTANCE: NetWork? = null
        init {
            if (INSTANCE == null) {
                synchronized(NetWork::class.java) {
                    if (INSTANCE == null) {
                        INSTANCE = NetWork()
                    }
                }
            }
        }
    }

    fun hospitalService(): HospitalService = getRetrofit().create(HospitalService::class.java)

    private fun getRetrofit(): Retrofit =
            Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(OkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(LiveDataCallAdapterFactory())
                    .build()

    private fun getOkHttpClientBuilder(): OkHttpClient.Builder {
        val loggingInterceptor = HttpLoggingInterceptor { message ->
            Log.e("OkHttp -->", message)
        }
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        val cacheFile = File(CustomApplication.INSTANCE.cacheDir, "cache")
        val cache = Cache(cacheFile, 1024 * 1024 * 100)

        return OkHttpClient.Builder()
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(HttpHeaderInterceptor())
                .addNetworkInterceptor(HttpCacheInterceptor())
                .cache(cache)
    }
}